<?php namespace App\Http\Controllers;

use App\Article;
use App\Doctors;
use App\DoctorTime;
use App\DoctorWeek;
use App\Exceptions\NotFoundException;
use App\FollowQrcode;
use App\Goods;
use App\Hospital;
use App\OrderItem;
use App\Orders;
use App\Packages;
use App\Questions;
use App\Referral;
use App\Services\Tools;
use App\Services\UserManager;
use App\User;
use App\UserAddress;
use App\UserInfo;
use App\UserXDoctor;
use EasyWeChat\Payment\Order;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;
use PhpParser\Comment\Doc;

class HomeController extends Controller {

	/*
	|--------------------------------------------------------------------------
	| Home Controller
	|--------------------------------------------------------------------------
	|
	| This controller renders your application's "dashboard" for users that
	| are authenticated. Of course, you are free to change or remove the
	| controller as you wish. It is just here to get your app started!
	|
	*/

	/**
	 * Create a new controller instance.
	 *
	 * @return void
	 */
//	public function __construct()
//	{
//		$this->middleware('auth');
//	}

	/**
	 * Show the application dashboard to the user.
	 *
	 * @return Response
	 */
	public function index(Request $request)
	{
//	    $user = $guard->user();
//	    var_dump($user);die;
		if(!UserManager::isLogin($request)){
//		        echo "111";die;
            return redirect(route('Api.Auth.weixinLogin'));
//            echo $guard->guest();
		}
        return view('index');

	}

	public function bespeak($id,Request $request){
        $user = UserManager::isLogin($request);

        if(!$user){
            return redirect(route('Api.Auth.weixinLogin'));
        }

        if((int)$user->role !== 0)
            return redirect(route('Api.Auth.weixinLogin'));

		/** @var UserInfo $userInfo */
		$userInfo = '';
		if ($user)
			$userInfo = UserInfo::whereUserId($user->id)->first();

        if(!$userInfo)
            return redirect(route('M.Home.userCenter'));

		if((int)$userInfo->status == 0)
			return redirect(route('M.Home.userCenter'));

		$doctor = Doctors::whereId($id)->first();

		if (!$doctor){
			header('location:'.route('M.Home.doctorList'));
		}
		else{
			$doctor->hugs = $doctor->hug()->where('hugh_date','=',date('Y-m-d',time()+ 60*60*24))->get();
            $times = array('9:00-10:00','10:00-11:00 ','11:00-12:00','14:30-15:30','15:30-16:30','16:30-17:30');
			return view('bespeak',['doctor'=>$doctor,'user_info'=>$userInfo,'times'=>$times]);
		}
	}

	public function packages(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=packages');
        }

        /** @var User $user */

        if((int)$user->role !== 0)
            return redirect(route('M.Doctor.orderList'));

		$packages = Packages::whereIsOff(0)->whereIsPersonal(0)->skip(0)->take(10)->orderBy('created_at','desc')->get();

		return view('packages',['packages'=>$packages]);
	}

	public function packageDetail($id,Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin'));
        }

        if((int)$user->role !== 0)
            return redirect(route('Api.Auth.weixinLogin'));

		$userInfo = '';
		if ($user)
			$userInfo = UserInfo::whereUserId($user->id)->first();

        if((int)$userInfo->status == 0)
            return redirect(route('M.Home.userCenter'));

		$package = Packages::whereId($id)->first();

		if (!$package){
			header('location:'.route('M.Home.packages'));
		}
		else{
			$package->hug;
			return view('packageDetail',['package'=>$package,'user_info'=>$userInfo]);
		}

	}

	public function keshiList(){
		$allArticle = Article::all();
		return view('keshi',['page'=>'home','articles'=>$allArticle]);
	}

	public function contentDetail(){
		$id = Input::get('id');
		$thatArticle = Article::find($id);
		return view('content_detail',['article'=>$thatArticle]);
	}

	public function userCenter(Guard $guard){
//		if($guard->guest()){
//			return redirect(route('Api.Auth.weixinLogin'));
//		}
//
//		/** @var User $user */
//		$user = $guard->user();
//
//        if((int)$user->role !== 0)
//            return redirect(route('Api.Auth.weixinLogin'));

//		$userInfo = $user->userInfo;
		return view('userCenter');
	}

	public function doctorList(Request $request){
	    $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin'));
        }

        if((int)$user->role !== 0)
            return redirect(route('Api.Auth.weixinLogin'));

		$doctors = Doctors::whereIsWork(1)->skip(0)->take(10)->orderBy('created_at','desc')->get();
		return view('doctor-list',['doctors'=>$doctors]);
	}

	/** 登出 */
	public function signOut(Request $request)
	{
        $cookie = Cookie::forget("user_token");
		return redirect()->to(route('M.Home.goods'))->cookie($cookie);
	}

	public function pay(){
		return view('test');
	}

	public function orderList(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin'));
        }

		$modelid = !is_null(Input::get('model')) ? Input::get('model') : 0;

		/** @var User $user */
        if((int)$user->role !== 0)
            return redirect(route('Api.Auth.weixinLogin'));

		$orders = null;
		switch((int)$modelid){
			case 0:
				$orders = Orders::whereUserId($user->id)->whereIspay(1)->orderBy('created_at','desc')->get();
				break;
			case 1:
				$orders = Orders::whereUserId($user->id)->whereIspay(1)->whereType('appoint')->orderBy('created_at','desc')->get();
				break;
			case 2:
				$orders = Orders::whereUserId($user->id)->whereIspay(1)->whereType('face')->orderBy('created_at','desc')->get();
				break;
            case 3:
                $orders = Orders::whereUserId($user->id)->whereIspay(1)->whereType('package')->orderBy('created_at','desc')->get();
                break;
		}

		foreach($orders as $order){
            /** @var Orders $order */
            $hospital = '';
            /** @var Hospital $thatHospital */
            $thatHospital = Hospital::whereId($order->hospital_id)->first();

            if($thatHospital)
                $hospital = $thatHospital->name;


			if($order->type == 'appoint'){
				/** @var Doctors $thatDoctor */
				$thatDoctor = Doctors::whereUserId($order->doctor_id)->first();
				if($thatDoctor){
					$order->img_id   = $thatDoctor->doc_img;
					$order->title    = $thatDoctor->doc_name."医生【门诊】";
                    $order->hospital = $hospital;
				}else{
					$order->img_id = 0;
					$order->title = "该医生已被删除";
				}

			}elseif($order->type == 'package'){
				/** @var Packages $thatPacket */
				$thatPacket = Packages::find($order->package_id);
				if($thatPacket){
					$order->title = $thatPacket->pak_name."【缴费项】";
					$order->img_id = $thatPacket->pak_img;
                    $order->hospital = $hospital;
				}else{
					$order->title = "该项目已经被删除";
					$order->img_id = 0;
				}

			}else{
                /** @var Doctors $thatDoctor */
                $thatDoctor = Doctors::whereUserId($order->doctor_id)->first();
                if($thatDoctor){
                    $order->img_id = $thatDoctor->doc_img;
                    $order->title = $thatDoctor->doc_name."医生【面诊】";
                }else{
                    $order->img_id = 0;
                    $order->title = "该医生已被删除";
                }
            }
		}

		$times = array('9:00-10:00','10:00-11:00 ','11:00-12:00','14:30-15:30','15:30-16:30','16:30-17:30');

		return view('order-list',['orders'=>$orders,'model'=>$modelid,'page'=>'usercenter','times'=>$times]);
	}

	public function newDoctorList(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=doctordetail');
        }

        $keyword = Input::get('keyword');

        $query = DB::table('doctors')->where('is_work','=',1)->whereNull('deleted_at');

        if(!is_null($keyword)){
            $query->where(function($q) use ($keyword){
                $q->where('doc_name','like','%'.$keyword.'%')->orWhere('introduction','like','%'.$keyword.'%')->orWhere('subject','like','%'.$keyword.'%');
            });
        }


        $allDoctors = $query->orderBy('created_at','desc')->get();

        foreach($allDoctors as $doctor){
            /** @var Doctors $doctor */
            $hospital = Hospital::whereId($doctor->hospital_id)->first();

            if($hospital){
                $doctor->hospital = $hospital->name;
            }else{
                $doctor->hospital = '';
            }
        }

        return view('new-doctors-list',['doctors'=>$allDoctors,'keyword'=>$keyword]);
    }

    public function newFollowDoctors(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=followDoctor');
        }

        /** @var User $user */

        $followQrcodes = FollowQrcode::whereOpenid($user->openid)->whereStatus(0)->get();

        if(count($followQrcodes)>0){
            foreach($followQrcodes as $followQrcode){
                /** @var FollowQrcode $followQrcode */
                $thatDoctor = Doctors::whereUserId($followQrcode->doc_id)->first();
                if($thatDoctor){
                    $hasFollow = UserXDoctor::whereUserId($user->id)->whereDoctorId($followQrcode->doc_id)->first();
                    if(!$hasFollow){
                        $hasFollow            = new UserXDoctor();
                        $hasFollow->user_id   = $user->id;
                        $hasFollow->doctor_id = $followQrcode->doc_id;
                        $hasFollow->save();
                    }
                }

                $followQrcode->status = 1;
                $followQrcode->save();
            }
        }

        $myFollowDocIds = UserXDoctor::whereUserId($user->id)->get();

        $docIds = array();
        foreach($myFollowDocIds as $myFollowDocId){
            array_push($docIds,$myFollowDocId->doctor_id);
        }

        $allDoctors = Doctors::whereIn('user_id',$docIds)->orderBy('created_at','desc')->get();

        foreach($allDoctors as $doctor){
            /** @var Doctors $doctor */
            $hospital = Hospital::whereId($doctor->hospital_id)->first();

            if($hospital){
                $doctor->hospital = $hospital->name;
            }
        }

        return view('new-follow-doctors',['doctors'=>$allDoctors]);
    }

    public function newDoctorDetail($id,Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=doctordetail');
        }

        /** @var Doctors $thatDoctor */
        $thatDoctor = Doctors::whereId($id)->first();

        $followDoctor = UserXDoctor::whereDoctorId($thatDoctor->user_id)->whereUserId($user->id)->first();

        $hospital = Hospital::whereId($thatDoctor->hospital_id)->first();

        $questions = Questions::whereDoctorId($thatDoctor->user_id)->whereNotNull('answer_time')->orderBy('created_at','desc')->limit(10)->offset(0)->get();

        foreach($questions as $question){
            /** @var Questions $question */
            /** @var Doctors $thatDoctor */
            $thatDoctor = Doctors::whereUserId($question->doctor_id)->first();
            if($thatDoctor){
                $question->doctor = $thatDoctor;

                $hospital = Hospital::whereId($thatDoctor->hospital_id)->first();

                if($hospital){
                    $thatDoctor->hospital = $hospital->name;
                }
            }
        }

        return view('new-doctor-detail',['doctor'=>$thatDoctor,'follow'=>$followDoctor,'hospital'=>$hospital,'questions'=>$questions]);
    }

    public function askDoctor(Request $request,$id){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=doctordetail');
        }

        $userInfo = UserInfo::whereUserId($user->id)->first();

        $doctor = Doctors::whereUserId($id)->first();

        return view('new-question',['user'=>$user,'userinfo'=>$userInfo,'doctor'=>$doctor]);
    }

    public function newMianzhen(Guard $guard,Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=usercenter');
        }

        /** @var User $user */

        if(!$user->userInfo || ($user->userInfo && $user->userInfo->status == 0))
            return redirect(route('M.Home.newUserCenterSet'));

        $docId = $request->get('doc_id');
        $day   = $request->get('day');
        $dayTime = $request->get('t');

        $doctor = Doctors::whereUserId($docId)->first();

        if($doctor){
            $hospital = Hospital::whereId($doctor->hospital_id)->first();

            if($hospital){
                $doctor->hospital = $hospital->name;
            }else{
                $doctor->hospital = '';
            }
        }else{
            $doctor->hospital = '';
        }

        return view('new-mianzhen',[
            'doctor' => $doctor,
            'day'    => $day,
            'day_time' => $dayTime,
            'userinfo' => $user->userInfo
        ]);
    }

    public function newUserCenter(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=usercenter');
        }
        /** @var User $user */

        $userInfo = $user->userInfo;
        return view('new-usercenter',['user'=>$user,'userinfo'=>$userInfo]);
    }

    public function newUserCenterSet(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=usercenter');
        }
        /** @var User $user */

        $userInfo = $user->userInfo;

        return view('new-usercenter-set',['user'=>$user,'userinfo'=>$userInfo]);
    }

    public function newFaceTime(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=usercenter');
        }

        $doctorId = $request->get('doc_id');

        /** @var User $user */
//        $dateOne = DoctorTime::whereUserId($doctorId)->whereType('face')->whereDays(date('Y-m-d',time()))->first();
//        $dateTwo = DoctorTime::whereUserId($doctorId)->whereType('face')->whereDays(date('Y-m-d',strtotime('+1 days')))->first();
//        $dateThree = DoctorTime::whereUserId($doctorId)->whereType('face')->whereDays(date('Y-m-d',strtotime('+2 days')))->first();
//        $dateFour = DoctorTime::whereUserId($doctorId)->whereType('face')->whereDays(date('Y-m-d',strtotime('+3 days')))->first();
//        $dateFire = DoctorTime::whereUserId($doctorId)->whereType('face')->whereDays(date('Y-m-d',strtotime('+4 days')))->first();
//        $dateSix = DoctorTime::whereUserId($doctorId)->whereType('face')->whereDays(date('Y-m-d',strtotime('+5 days')))->first();
//        $dateSeven = DoctorTime::whereUserId($doctorId)->whereType('face')->whereDays(date('Y-m-d',strtotime('+6 days')))->first();

        $dateOne   = DoctorWeek::whereUserId($doctorId)->whereType('face')->whereWeek(Tools::getWeekNum(time()))->first();
        $dateTwo   = DoctorWeek::whereUserId($doctorId)->whereType('face')->whereWeek(Tools::getWeekNum(strtotime('+1 days')))->first();
        $dateThree = DoctorWeek::whereUserId($doctorId)->whereType('face')->whereWeek(Tools::getWeekNum(strtotime('+2 days')))->first();
        $dateFour  = DoctorWeek::whereUserId($doctorId)->whereType('face')->whereWeek(Tools::getWeekNum(strtotime('+3 days')))->first();
        $dateFire  = DoctorWeek::whereUserId($doctorId)->whereType('face')->whereWeek(Tools::getWeekNum(strtotime('+4 days')))->first();
        $dateSix   = DoctorWeek::whereUserId($doctorId)->whereType('face')->whereWeek(Tools::getWeekNum(strtotime('+5 days')))->first();
        $dateSeven = DoctorWeek::whereUserId($doctorId)->whereType('face')->whereWeek(Tools::getWeekNum(strtotime('+6 days')))->first();

        return view('new-face-time',[
            'date_one'=>$dateOne,
            'date_two'=>$dateTwo,
            'date_three'=>$dateThree,
            'date_four'=>$dateFour,
            'date_fire'=>$dateFire,
            'date_six'=>$dateSix,
            'date_seven'=>$dateSeven,
            'doc_id'    => $doctorId
        ]);
    }


    public function newAppoint(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=usercenter');
        }

        /** @var User $user */

        if(!$user->userInfo || ($user->userInfo && $user->userInfo->status == 0))
            return redirect(route('M.Home.newUserCenterSet'));

        $docId = $request->get('doc_id');
        $day   = $request->get('day');
        $dayTime = $request->get('t');

        $doctor = Doctors::whereUserId($docId)->first();

        if($doctor){
            $hospital = Hospital::whereId($doctor->hospital_id)->first();

            if($hospital){
                $doctor->hospital = $hospital->name;
            }else{
                $doctor->hospital = '';
            }
        }else{
            $doctor->hospital = '';
        }

        return view('new-appoint',[
            'doctor' => $doctor,
            'day'    => $day,
            'day_time' => $dayTime,
            'userinfo' => $user->userInfo
        ]);
    }

    public function newAppointTime(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=usercenter');
        }

        $doctorId = $request->get('doc_id');

        /** @var User $user */
        $dateOne   = DoctorWeek::whereUserId($doctorId)->whereType('appoint')->whereWeek(Tools::getWeekNum(time()))->first();
        $dateTwo   = DoctorWeek::whereUserId($doctorId)->whereType('appoint')->whereWeek(Tools::getWeekNum(strtotime('+1 days')))->first();
        $dateThree = DoctorWeek::whereUserId($doctorId)->whereType('appoint')->whereWeek(Tools::getWeekNum(strtotime('+2 days')))->first();
        $dateFour  = DoctorWeek::whereUserId($doctorId)->whereType('appoint')->whereWeek(Tools::getWeekNum(strtotime('+3 days')))->first();
        $dateFire  = DoctorWeek::whereUserId($doctorId)->whereType('appoint')->whereWeek(Tools::getWeekNum(strtotime('+4 days')))->first();
        $dateSix   = DoctorWeek::whereUserId($doctorId)->whereType('appoint')->whereWeek(Tools::getWeekNum(strtotime('+5 days')))->first();
        $dateSeven = DoctorWeek::whereUserId($doctorId)->whereType('appoint')->whereWeek(Tools::getWeekNum(strtotime('+6 days')))->first();

        return view('new-appoint-time',[
            'date_one'=>$dateOne,
            'date_two'=>$dateTwo,
            'date_three'=>$dateThree,
            'date_four'=>$dateFour,
            'date_fire'=>$dateFire,
            'date_six'=>$dateSix,
            'date_seven'=>$dateSeven,
            'doc_id'    => $doctorId
        ]);
    }

    public function newMyQuestions(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=usercenter');
        }

        /** @var User $user */

        $questions = Questions::whereUserId($user->id)->get();

        foreach($questions as $question){
            /** @var Questions $question */
            /** @var Doctors $thatDoctor */
            $thatDoctor = Doctors::whereUserId($question->doctor_id)->first();
            if($thatDoctor){
                $question->doctor = $thatDoctor;

                $hospital = Hospital::whereId($thatDoctor->hospital_id)->first();

                if($hospital){
                    $thatDoctor->hospital = $hospital->name;
                }
            }
        }

        return view('new-my-questions',['questions'=>$questions]);
    }

    public function newShowAnswer(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=usercenter');
        }

        /** @var User $user */

        $questionId = Input::get('q_id');

        /** @var Questions $thatQuestion */
        $thatQuestion = Questions::whereId($questionId)->first();

        if(!$thatQuestion)
            throw new NotFoundException(NotFoundException::DataNotFound);

        $thatQuestion->read_num = $thatQuestion->read_num + 1;
        $thatQuestion->save();

        /** @var Doctors $doctor */
        $doctor = Doctors::whereUserId($thatQuestion->doctor_id)->first();

        $hospital = Hospital::whereId($doctor->hospital_id)->first();

        return view('new-show-answer',['question'=>$thatQuestion,'doctor'=>$doctor,'hospital'=>$hospital]);
    }

    public function referralPay(Request $request){
        $referralId = $request->get('referral_id');

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin'));
        }

        if($user->role == 1){
            echo "不允许访问";die;
        }

        /** @var Referral $thatReferral */
        $thatReferral = Referral::whereId($referralId)->whereUserId($user->id)->first();
        if(!$thatReferral){
            echo "链接错误";die;
        }

        /** @var Doctors $drDoctorInfo */
        $drDoctorInfo = Doctors::whereUserId($thatReferral->dr_user_id)->first();
        if(!$drDoctorInfo){
            echo "医生不存在";die;
        }

        /** @var UserInfo $userInfo */
        $userInfo = UserInfo::whereUserId($thatReferral->user_id)->first();
        if(!$userInfo){
            echo "用户不存在";die;
        }

        $thatOrder = new Orders();
        $thatOrder->doctor_id     = $thatReferral->dr_user_id;
        $thatOrder->order_num     = Tools::makeBillNum();
        $thatOrder->order_price   = $thatReferral->amount;
        $thatOrder->patient_name  = $userInfo->realname;
        $thatOrder->patient_phone = $userInfo->phone;
        $thatOrder->patient_birth = $userInfo->birthday;
        $thatOrder->hospital_id   = $drDoctorInfo->hospital_id;
        $thatOrder->type          = "referral";
        $thatOrder->save();

        $thatReferral->order_num = $thatOrder->order_num;
        $thatReferral->save();

        $thatHospital = Hospital::whereId($drDoctorInfo->hospital_id)->first();

        return view("referral-pay",["referral"=>$thatReferral,"hospital"=>$thatHospital,"doctor"=>$drDoctorInfo,"userinfo"=>$userInfo]);
    }

}
